package com.zc.im.netty.codec;

import com.zc.im.common.msg.Msg;
import com.zc.im.common.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Project：im
 * Date：2022/4/21
 * Time：14:21
 * Description：im自定义解码器
 *
 * @author Challen.Zhang
 * @version 1.0
 */
public class ImEncoder extends MessageToByteEncoder<Msg> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Msg msg, ByteBuf byteBuf) throws Exception {
        byte[] bytes = ProtostuffUtil.serializer(msg);
        //写入报文长度
        byteBuf.writeInt(bytes.length);
        //写入mgs类型
        byteBuf.writeByte(msg.getType().getValue());
        //写入数据
        byteBuf.writeBytes(bytes);
    }
}
